using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Data;

namespace ESBSimpleSamples.ServiceClient.Helpers
{
    public static class SerializationHelper
    {
        public static T ChangeType<T>(object value)
        {
            XmlSerializer fromSerializer = new XmlSerializer(value.GetType());
            MemoryStream stream = new MemoryStream();
            fromSerializer.Serialize(stream, value);
            return ChangeType<T>(stream);
        }

        public static T ChangeType<T>(XmlNode node)
        {
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, null);
            node.WriteTo(writer);
            writer.Flush();
            return ChangeType<T>(stream);            
        }

        private static T ChangeType<T>(Stream stream)
        {
            stream.Position = 0;
            object returnValue;
            if (typeof(T).UnderlyingSystemType == typeof(DataSet).UnderlyingSystemType)
            {
                DataSet returnDs = new DataSet();
                returnDs.ReadXml(stream, XmlReadMode.DiffGram);
                returnValue = returnDs;
            }
            else
            {
                XmlSerializer toSerializer = new XmlSerializer(typeof(T));
                returnValue = toSerializer.Deserialize(stream);
            }
            return (T)returnValue;
        }

        public static XmlNode Serialize(object value)
        {
            XmlSerializer fromSerializer = new XmlSerializer(value.GetType());
            MemoryStream stream = new MemoryStream();
            fromSerializer.Serialize(stream, value);
            stream.Position = 0;
            XmlTextReader reader = new XmlTextReader(stream);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            return doc;
        }
    }
}
